package git.soulbgm.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import git.soulbgm.pojo.AlarmInfo;
import git.soulbgm.service.AlarmInfoService;
import git.soulbgm.utils.DateUtil;
import git.soulbgm.utils.LogHelper;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 删除告警信息的任务
 *
 * @author SoulBGM
 * @date 2023-04-25
 */
@Component
public class DeleteAlarmInfoTask {

    private static final LogHelper LOG = new LogHelper(DeleteAlarmInfoTask.class);
    private final AlarmInfoService service;

    public DeleteAlarmInfoTask(AlarmInfoService service) {
        this.service = service;
    }

    @Scheduled(cron = "${jobs.map.deleteAlarmInfo.cron}")
    @SchedulerLock(name = "${jobs.map.deleteAlarmInfo.name}", lockAtMostFor = "${jobs.map.deleteAlarmInfo.lockAtMostFor}", lockAtLeastFor = "${jobs.map.deleteAlarmInfo.lockAtLeastFor}")
    public void execute() throws Exception {
        Calendar calendar = DateUtil.getStartCalendar(DateUtil.getCalendar(), DateUtil.MONTH);
        DateUtil.offsetDate(calendar, DateUtil.MONTH, -1);
        LambdaQueryWrapper<AlarmInfo> wrapper = new LambdaQueryWrapper<>();
        Date time = calendar.getTime();
        wrapper.eq(AlarmInfo::getMachineHandle, HANDLE_COMPLETE)
                .eq(AlarmInfo::getReadHandle, HANDLE_COMPLETE)
                .eq(AlarmInfo::getArtificialHandle, HANDLE_COMPLETE)
                .lt(AlarmInfo::getCreateTime, time);
        int result = service.getBaseMapper().delete(wrapper);
        LOG.info("删除 {} 时间之前(不包含)已读，已处理的告警内容，删除条数 {}", DateUtil.format(time, DateUtil.NORM_DATETIME_MS_PATTERN), result);
    }

}
